import React from 'react';
import { useReducer } from 'react'
// 引入Son1 和Son2
import Son1 from './Son1';
import Son2 from './Son2';
import contextObj from './context'
const { Provider } = contextObj
// useReducer:
// 作用: 当页面中部分组件有公共的状态, 那么可以使用useReducer 去定义一个局部的仓库.
// 然后这几个组件共用这些状态,并维护这些状态,

// 语法: 
// 步骤1: 定义初始的数据
const defaultState = {
    count: 0,
    user: {
        name: '秦涵',
        age: 19
    }
}
// 步骤2: 定义操作该小仓库数据的reducer
const reducer = (state, action) => {
    //进行修改state 的操作
    if (action.type == '+') {
        return {
            ...state,
            count: state.count + action.payload
        }
    }

    if (action.type == 'addAge') {
        return {
            ...state,
            user: {
                ...state.user,
                age: state.user.age + action.payload
            }
        }
    }

    return state

}

const Father = () => {

    const [state, dispatch] = useReducer(reducer, defaultState)
    return (
        <div>
            <p onClick={() => {
                dispatch({ type: '+', payload: 10 })
            }}>父-count:{state.count}</p>
            {/* 使用子组件 */}
            <Provider value={{
                state,
                dispatch
            }}>
                <Son1></Son1>
                <Son2></Son2>
            </Provider>
        </div>
    );
}

export default Father;
